#include "BitmapFont.h"
#include "../SGD Wrappers/CSGD_TextureManager.h"
#include <cassert>


CBitmapFont::CBitmapFont(void)
{
	m_nCharWidth = -1;
	m_nCharHeight =-1;
	m_nNumCols =   -1;
	m_nNumRows =   -1;
	m_nNumRows =   -1;
	m_nImageID=	   -1;
	m_cFirstChar= 0;
	m_bOnlyUpper=	   false;
}


CBitmapFont::~CBitmapFont(void)
{
}

void CBitmapFont::Initialize( void )
	{
		m_nCharWidth = 32;
		m_nCharHeight = 32;
		m_nNumCols = 10;
		m_nNumRows = 6;
		m_nImageID = CSGD_TextureManager::GetInstance()->LoadTexture(_T("Resources/Graphics/BitmapFont.png"));
		m_cFirstChar = 32;
		//m_bOnlyUpper = true;
	}

void CBitmapFont::Print( const char* szText,	int nX, int nY,
				   float fScale )
	{
		// Keep track of the starting x position (for newlines)
		int nColStart = nX;

		// Iterate through the string 1 char at a time
		int nLength = strlen(  szText );

		for( int i = 0; i < nLength; i++ )
		{
			// Get the character out of the string
			char ch = szText[ i ];

			// Check for whitespace
			if( ch == ' ' || ch == '\t' )
			{
				nX += m_nCharWidth * fScale;
				continue;
			}
			else if( ch == '\n' )
			{
				nY += m_nCharHeight * fScale;
				nX =  nColStart;
				continue;
			}


			// Convert to uppercase?
			//if( m_bOnlyUpper )
			//	ch = toupper( ch );


			// Convert the ASCII character to a tile id
			int id = ch - m_cFirstChar;

			// Use the CellAlgorithm to calculate the source rect
			RECT rChar = CellAlgorithm( id );

			// Render!
			CSGD_TextureManager::GetInstance()->Draw( m_nImageID, nX, nY, fScale, fScale,
						 &rChar, 0.0f, 0.0f, 0.0f );

			// Move to the next position on screen
			nX += m_nCharWidth * fScale;
		}

};

RECT CBitmapFont::CellAlgorithm( int id )
{
	// sanity-check
	assert( id >= 0 && id <= m_nNumCols*m_nNumRows-1 );


	// Calculate row & column based on the tile id and
	// the number of columns in the image
	// row == id / 7
	// col == id % 7
	
	RECT rSource = { };



	rSource.left	= (id % m_nNumCols) * m_nCharWidth;
	rSource.top		= (id / m_nNumCols) * m_nCharHeight;

	rSource.right	= rSource.left + m_nCharWidth;
	rSource.bottom	= rSource.top  + m_nCharHeight;

	return rSource;
}